package com.example.myapplication.zuoye;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.browse.MediaBrowser;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;
import android.widget.VideoView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.core.content.FileProvider;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.CoordType;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapView;
import com.example.myapplication.MainActivity;
import com.example.myapplication.MyApp;
import com.example.myapplication.R;
import com.example.myapplication.FileUtil;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class LoginActivity extends AppCompatActivity {

    private AppCompatEditText usernameEditText;
    private AppCompatEditText passwordEditText;

    private AppCompatButton loginButton;
    private AppCompatButton cancelbutton;
    private AppCompatButton camera1Button;

    private AppCompatButton videoButton;
    private AppCompatButton video1Button;

    private AppCompatButton cropButton;

    private AppCompatImageView mainImageView;
    private VideoView mainvideoView;
    private MapView mainmapView;

    private File file;

    public LocationClient mLocationClient = null;
    private BdLocationListener bdLocationListener = new BdLocationListener();

    @SuppressLint("WrongViewCast")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        /*
        usernameEditText = findViewById(R.id.usernameEditText);
        passwordEditText = findViewById(R.id.passwordEditText);
        loginButton = findViewById(R.id.loginButton);
        cancelbutton = findViewById(R.id.cancelbutton);
        camera1Button = findViewById(R.id.camera1Button);
        cropButton = findViewById(R.id.cropButton);
        mainvideoView = findViewById(R.id.mainvideoview);
        videoButton = findViewById(R.id.videoButton);
        video1Button = findViewById(R.id.video1Button);
        */
        mainImageView = findViewById(R.id.mainImageView);

        mLocationClient = new LocationClient(getApplicationContext());
        mLocationClient.registerLocationListener(bdLocationListener);


        //配置百度
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setIsNeedAddress(true);
        option.setNeedNewVersionRgc(true);
        mLocationClient.setLocOption(option);
        option.setCoorType("bd09ll");
        option.setScanSpan(1000);
        option.setOpenGps(true);
        mLocationClient.setLocOption(option);
        mLocationClient.start();
        SDKInitializer.initialize(this);
        SDKInitializer.setCoordType(CoordType.BD09LL);
        /*
        mBaiduMap = mMapView.getMap();
        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);*/



        ArrayList<String> files = getFilesAllName("/sdcard/Movies");
        for (int i = 0; i < files.size(); i++) {
            if (files.get(i).contains(".mp4")) {
                File file = new File(files.get(i));
                mainvideoView.setVideoURI(Uri.fromFile(file));
                mainvideoView.start();
                break;
            }
        }


        String key = MyApp.get().getSharedPreferences().getString("key", "");
        if (!key.isEmpty()) {
            startActivity(new Intent(LoginActivity.this, MainActivity.class));
            finish();
        }

        loginButton.setOnClickListener(view -> {
            String mobile = usernameEditText.getText().toString();
            String password = passwordEditText.getText().toString();
            if (mobile.isEmpty()) {
                Toast.makeText(this, "用户名不能为空", Toast.LENGTH_SHORT).show();
                return;
            }
            if (!isMobileNO(mobile)) {
                Toast.makeText(this, "请输入有效的手机号码", Toast.LENGTH_SHORT).show();
                return;
            }
            if (password.isEmpty()) {
                Toast.makeText(this, "密码不能为空", Toast.LENGTH_SHORT).show();
                return;
            }
            if (password.length() < 6) {
                Toast.makeText(this, password, Toast.LENGTH_SHORT).show();
                Toast.makeText(this, "请输入有效的密码", Toast.LENGTH_SHORT).show();
                return;
            }
            OkGo.<String>post("https://demo.shopwt.com/api/mobile/index.php?w=login")
                    .params("username", mobile)
                    .params("password", password)
                    .params("client", "wap")
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(Response<String> response) {
                            try {
                                JSONObject jsonObject = new JSONObject(response.body().toString());
                                if (jsonObject.getInt("code") == 400) {
                                    jsonObject = jsonObject.getJSONObject("datas");
                                    Toast.makeText(LoginActivity.this, jsonObject.getString("error"), Toast.LENGTH_SHORT).show();
                                    return;
                                }
                                jsonObject = jsonObject.getJSONObject("datas");
                                String key = jsonObject.getString("key");
                                MyApp.get().getEditor().putString("key", key).apply();
                                Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                                startActivity(new Intent(LoginActivity.this, MainActivity.class));
                                finish();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
        });
        cancelbutton.setOnClickListener(view -> {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(intent, 999);
        });


        camera1Button.setOnClickListener(view -> {
            file = FileUtil.createFile(
                    getExternalMediaDirs()[0].getAbsolutePath(),
                    "learn2",
                    "jpg"
            );
            if (file != null) {
                Uri uri = FileProvider.getUriForFile(this, "top.yokey.learnl.fileProvider", file);
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                startActivityForResult(intent, 1000);
            }
        });

        cropButton.setOnClickListener(view -> {
            Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            intent.setType("image/*");
            startActivityForResult(intent, 1001);
        });
        videoButton.setOnClickListener(view -> {
            Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            intent.setType("video/*");
            startActivityForResult(intent, 1003);
        });
        //打开相机录制视频并播放
        video1Button.setOnClickListener(view -> {
            Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            intent.setType("video/*");
            startActivityForResult(intent, 1004);
        });
    }




    @Override
    protected void onResume() {
        super.onResume();
        mainmapView.onResume();
    }
    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mainmapView.onPause();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mainmapView.onDestroy();
    }



    public static boolean isMobileNO(String mobiles) {
        Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
        Matcher m = p.matcher(mobiles);
        System.out.println(m.matches() + "---");
        return m.matches();
    }


    @Override
    protected void onPostResume() {
        super.onPostResume();
        XXPermissions.with(this).permission(getPermissions1()).request(new OnPermissionCallback() {
            @Override
            public void onGranted(List<String> permissions, boolean all) {

            }

            @Override
            public void onDenied(List<String> permissions, boolean never) {
                //权限被拒接或者部分权限未完整授权
                Log.d("TAGS", "123");
            }
        });


    }

    private String[] getPermissions1() {
        return new String[]{
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.CAMERA,//拍照权限
                Manifest.permission.READ_EXTERNAL_STORAGE,//读外部存储
                Manifest.permission.WRITE_EXTERNAL_STORAGE,//写外部存储
        };
    }

    //读取文件
    private ArrayList<String> getFilesAllName(String path) {
        File file = new File(path);
        File[] files = file.listFiles();
        if (files == null) {
            return null;
        }
        ArrayList<String> list = new ArrayList<>();
        for (int i = 0; i < files.length; i++) {
            list.add(files[i].getAbsolutePath());
        }
        return list;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 999) {
                Bitmap bitmap = data.getExtras().getParcelable("data");
                mainImageView.setImageBitmap(bitmap);
            }
            if (requestCode == 1000) {
                Log.d("TAGS", file.getAbsolutePath());
                mainImageView.setImageURI(Uri.fromFile(file));
            }
            if (requestCode == 1001) {
                file = FileUtil.createFile(
                        getExternalMediaDirs()[0].getAbsolutePath(),
                        "learn2",
                        "jpg"
                );
                Intent cropIntent = new Intent("com.android.camera.action.CROP");//跳到系统裁剪界面
                cropIntent.setDataAndType(data.getData(), "image/*");//设置裁剪图片的数据源
                cropIntent.putExtra("crop", "true");//设置裁剪
                cropIntent.putExtra("aspectX", 1);
                cropIntent.putExtra("aspectY", 1);
                cropIntent.putExtra("outputX", 500);
                cropIntent.putExtra("outputY", 500);
                cropIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
                cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.parse("file://" + file.getAbsolutePath()));
                cropIntent.putExtra("return-data", "false");
                startActivityForResult(cropIntent, 1002);
                FileUtil.showInAlbum(this, file.getAbsolutePath());
            }
            if (requestCode == 1002) {
                mainImageView.setImageURI(Uri.fromFile(file));
            }
            if (requestCode == 1003) {
                Uri uri = data.getData();
                mainvideoView.setVideoURI(uri);
                mainvideoView.start();
            }
            if (requestCode == 1004) {
                Uri uri = data.getData();
                mainvideoView.setVideoURI(uri);
                mainvideoView.start();
            }
        }

    }

    public class BdLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            double latitude = location.getLatitude();    //获取纬度信息
            double longitude = location.getLongitude();    //获取经度信息
            float radius = location.getRadius();    //获取定位精度，默认值为0.0f
            String coorType = location.getCoorType();
            //获取经纬度坐标类型，以LocationClientOption中设置过的坐标类型为准
            int errorCode = location.getLocType();
            //获取定位类型、定位错误返回码，具体信息可参照类参考中BDLocation类中的说明
            String addr = location.getAddrStr();    //获取详细地址信息
            String country = location.getCountry();    //获取国家
            String province = location.getProvince();    //获取省份
            String city = location.getCity();    //获取城市
            String district = location.getDistrict();    //获取区县
            String street = location.getStreet();    //获取街道信息
            String adcode = location.getAdCode();    //获取adcode
            String town = location.getTown();    //获取乡镇信息
            Log.d("TAGS", latitude + "|" + longitude);
            Log.d("TAGS", addr + "|" + country);
        }

    }
}

